from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import json
from fake_useragent import UserAgent

import configparser
cp = configparser.ConfigParser()
cp.read('account.cfg')


def login(username, password):
    url = "https://index.so.com/"
    chrome_options = Options()
    # ua = UserAgent()
    # chrome_options.add_argument('user-agent={}'.format(ua.random))
    # chrome_options.add_argument('--headless')
    # prefs = {"profile.managed_default_content_settings.images": 2}
    # chrome_options.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get(url)
    driver.implicitly_wait(10)
    driver.set_window_size(1920, 1080)
    driver.find_element_by_xpath('//a[contains(text(),"登录")]').click()
    time.sleep(3)
    driver.find_element_by_xpath('//input[contains(@name,"account")]').clear()
    driver.find_element_by_xpath('//input[contains(@name,"password")]').clear()
    driver.find_element_by_xpath('//input[contains(@name,"account")]').send_keys(username)
    driver.find_element_by_xpath('//input[contains(@name,"password")]').send_keys(password)
    driver.find_element_by_xpath('//input[contains(@type,"submit")]').click()
    time.sleep(3)
    cookies_list = driver.get_cookies()
    # print(cookies_list)
    driver.close()
    return cookies_list


if __name__ == '__main__':
    username = cp.get('360', 'USERNAME')
    password = cp.get('360', 'PASSWORD')
    cookies_list = login(username, password)
    print('Cookies获取成功...')
    with open('cookies/360_cookies.txt', 'w', encoding="utf-8") as f:
        f.write(json.dumps(cookies_list))
